import { ChangeDetectionStrategy, Component, ElementRef, EventEmitter, Input, Output, ViewChild } from '@angular/core'; 
import { CommonModule } from '@angular/common';  
import { CdkDragHandle, CdkDrag } from '@angular/cdk/drag-drop';
import { MatButtonModule } from '@angular/material/button';
import { MatIconModule } from '@angular/material/icon';
import { MatToolbarModule } from '@angular/material/toolbar';
import { DomSanitizer } from '@angular/platform-browser';
import { CdkMenuModule } from '@angular/cdk/menu';
import { OpenApiService } from '../../service/open-api.service';
import { Connection } from 'penpal';  
import { SafeUrlPipe } from '../../service/safeUrlPipe';

@Component({
  selector: 'app-window-cmp',
  standalone: true,
  imports: [CommonModule,CdkDragHandle,CdkDrag,MatToolbarModule,MatButtonModule, MatIconModule,CdkMenuModule, SafeUrlPipe],
  templateUrl: './window-cmp.component.html',
  styleUrl: './window-cmp.component.sass',

  changeDetection: ChangeDetectionStrategy.OnPush
})
export class WindowCmpComponent { 

  // 窗口id
  @Input("id") id!:number;

  // 标题
  @Input("title") title = "测试窗口"

  @Input("iconUrl") iconUrl?: string; // 图标


  // 地址 
  @Input("url")   url = "https://www.baidu.com";
  // page
  @ViewChild('page') page!: ElementRef<HTMLIFrameElement>;
  
  constructor(private sanitizer: DomSanitizer,private openApiSvc: OpenApiService) { 

  }

  ngOnInit(): void {
  }
 
@Input("isActive") isActive = true;

  //* 头部 */ 
  @Output() sizeMin = new EventEmitter<number>();  
  @Output() sizeMax = new EventEmitter<number>(); 
  @Output() sizeCommon = new EventEmitter<number>();  
  @Output() close = new EventEmitter<number>(); 
  
  //* 窗口大小 */
  @Input("isSizeMax") isSizeMax = false;
  _sizeMax() {
    this.isSizeMax = true;
    this.sizeMax.emit(this.id);
  } 
  _sizeCommon() {
    this.isSizeMax = false;
    this.sizeCommon.emit(this.id);
  } 

  // 前进
  public forward() {
    this.page.nativeElement.contentWindow?.history.forward();
  }

  // 后退
  public back() {
    this.page.nativeElement.contentWindow?.history.back();
  }

  // 刷新
  public refresh() {
    this.page.nativeElement.contentWindow?.location.reload();
  }

  // 在浏览器打开
  public openOnBrowserTab(){
    window.open(this.url,"_blank")
  }
 
  // 加载链接openapi
  link: Connection | null = null;
  ngAfterViewInit(): void {
    if (this.page) {
      this.page.nativeElement.onload = async () => { 
        if(this.link) return;
        this.link = this.openApiSvc.link(this.page.nativeElement);
        await this.link?.promise;
      };
    }
  } 
  
  // 组件声明钩子，销毁时，进行销毁link
  ngOnDestroy(): void {
    if (this.link) {
      this.link.destroy();
      this.link = null;
    }
  }



}
